package com.jsh.action.basic;

import com.jsh.base.BaseAction;
import com.jsh.base.Log;
import com.jsh.model.po.Logdetails;
import com.jsh.model.po.Authorization;
import com.jsh.model.po.Bom;
import com.jsh.model.vo.basic.BomModel;
import com.jsh.service.basic.BomService;
import com.jsh.service.basic.AuthorizationIService;
import com.jsh.service.basic.BomIService;
import com.jsh.service.basic.UserBusinessIService;
import com.jsh.util.BomConstants;
import com.jsh.util.JshException;
import com.jsh.util.PageUtil;
import com.jsh.util.Tools;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.dao.DataAccessException;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/*
 * 单位管理
 * @author ji-sheng-hua  qq:7 5 2 7 1 8 9 2 0
*/
@SuppressWarnings("serial")
public class BomAction extends BaseAction<BomModel>
{
	private BomIService BomService;
	private AuthorizationIService authorizationService;
    private UserBusinessIService userBusinessService;
	private BomModel model = new BomModel();
	private final static Integer ISYSTEM = 1;
    public static final String EXCEL = "excel";  //action返回excel结果
    public JSONObject jsonObject;
    
    private static final String TokenURL = "https://sso.digikey.com/as/token.oauth2?client_id=6ca977ca-678d-48f1-9a0a-d352bd35933d&"
    		+ "client_secret=aS4hW6iW8aB8jA6kQ7gF8vU4mV0wK5gY1sE5oK8jW8xQ4uB1cH&grant_type=refresh_token&refresh_token=";
	/**
	 * 增加BOM
	 * @return
	 */
	public void create()
	{
	    Log.infoFileSync("==================开始调用增加BOM方法===================");
	    Boolean flag = false;
	    String str="";
		try
		{
		    Bom bom = new Bom();
		    bom.setItem(model.getItem());
		    bom.setQty(model.getQty());
		    bom.setRef_designator(model.getRef_designator());
		    bom.setComplete_part(model.getComplete_part());
            bom.setDescription(model.getDescription());
            bom.setPakage_type_or_doc_type(model.getPakage_type_or_doc_type());
		    bom.setValue_or_rev(model.getValue_or_rev());
		    bom.setVoltage(model.getVoltage());
		    bom.setTolerances(model.getTolerances());
		    bom.setSpecial_comments(model.getSpecial_comments());
		    bom.setRohs(model.getRohs());
            bom.setTemperature_range(model.getTemperature_range());
            bom.setDescription(model.getDescription());
            bom.setManufacturer(model.getManufacturer());
		    bom.setSupplier(model.getSupplier());
		    bom.setSupplier_part_no(model.getSupplier_part_no());
		    bom.setSecond_source_manufacturer(model.getSecond_source_manufacturer());
		    bom.setSecond_source_part_no(model.getSecond_source_part_no());
		    bom.setDr_rart_number(model.getDr_rart_number());
		    BomService.create(bom);
			//========标识位===========
			flag = true;
			//记录操作日志使用
			tipMsg = "成功";
            tipType = 0;
		}
		catch (DataAccessException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>>增加BOM异常", e);
			flag = false;
			tipMsg = "失败";
            tipType = 1;
		}
		finally
		{
		    try 
		    {
                toClient(flag.toString());
            } 
		    catch (IOException e) 
		    {
                Log.errorFileSync(">>>>>>>>>>>>增加BOM回写客户端结果异常", e);
            }
		}
		
		logService.create(new Logdetails(getUser(), "增加BOM", model.getClientIp(),
                new Timestamp(System.currentTimeMillis())
        , tipType, "增加BOM名称为  "+ model.getItem() + " " + tipMsg + "！", "增加BOM" + tipMsg));
		Log.infoFileSync("==================结束调用增加BOM方法===================");
	}
	/**
	 * 删除BOM
	 * @return
	 */
	public String delete()
	{
	    Log.infoFileSync("====================开始调用删除BOM信息方法delete()================");
	    try 
	    {
            BomService.delete(model.getBomID());
            tipMsg = "成功";
            tipType = 0;
        } 
	    catch (DataAccessException e) 
	    {
	        Log.errorFileSync(">>>>>>>>>>>删除ID为 " + model.getBomID() + "  的供应商异常", e);
	        tipMsg = "失败";
            tipType = 1;
        }
	    model.getShowModel().setMsgTip(tipMsg);
	    logService.create(new Logdetails(getUser(), "删除Bom", model.getClientIp(),
	            new Timestamp(System.currentTimeMillis())
	    , tipType, "删除BomID为  "+ model.getBomID() + ",名称为  " + model.getItem() + tipMsg + "！", "删除Bom" + tipMsg));
	    Log.infoFileSync("====================结束调用删除Bom信息方法delete()================");
	    return SUCCESS;
	}

	
	/**
	 * 更新BOM
	 * @return
	 */
	public void update()
	{
	    Boolean flag = false;
	    String str="";
        try
        {
        	Bom bom = BomService.get(model.getBomID());
        	System.out.println(bom);
		    bom.setItem(model.getItem());
		    bom.setQty(model.getQty());
		    bom.setRef_designator(model.getRef_designator());
		    bom.setComplete_part(model.getComplete_part());
            bom.setDescription(model.getDescription());
            bom.setPakage_type_or_doc_type(model.getPakage_type_or_doc_type());
		    bom.setValue_or_rev(model.getValue_or_rev());
		    bom.setVoltage(model.getVoltage());
		    bom.setTolerances(model.getTolerances());
		    bom.setSpecial_comments(model.getSpecial_comments());
		    bom.setRohs(model.getRohs());
            bom.setTemperature_range(model.getTemperature_range());
            bom.setDescription(model.getDescription());
            bom.setManufacturer(model.getManufacturer());
		    bom.setSupplier(model.getSupplier());
		    bom.setSupplier_part_no(model.getSupplier_part_no());
		    bom.setSecond_source_manufacturer(model.getSecond_source_manufacturer());
		    bom.setSecond_source_part_no(model.getSecond_source_part_no());
		    bom.setDr_rart_number(model.getDr_rart_number());
		    
            
		    bom.setEnabled(bom.getEnabled());
            BomService.update(bom);
            
            flag = true;
            tipMsg = "成功";
            tipType = 0;
        } 
        catch (DataAccessException e) 
        {
            Log.errorFileSync(">>>>>>>>>>>>>修改BomID为 ： " + model.getBomID() + "信息失败", e);
            flag = false;
            tipMsg = "失败";
            tipType = 1;
        }
        finally
        {
            try 
            {
                toClient(flag.toString());
            } 
            catch (IOException e) 
            {
                Log.errorFileSync(">>>>>>>>>>>>修改Bom回写客户端结果异常", e);
            }
        }
        logService.create(new Logdetails(getUser(), "更新Bom", model.getClientIp(),
                new Timestamp(System.currentTimeMillis())
        , tipType, "更新BomID为  "+ model.getBomID() + " " + tipMsg + "！", "更新BOM" + tipMsg));
	}
	
	/**
	 * 批量删除指定IDBom
	 * @return
	 */
	public String batchDelete()
	{
	    try
	    {
            BomService.batchDelete(model.getBomIDs());
            model.getShowModel().setMsgTip("成功");
            //记录操作日志使用
            tipMsg = "成功";
            tipType = 0;
        } 
	    catch (DataAccessException e) 
	    {
	        Log.errorFileSync(">>>>>>>>>>>批量删除BomID为：" + model.getBomIDs() + "信息异常", e);
	        tipMsg = "失败";
            tipType = 1;
        }
	    
	    logService.create(new Logdetails(getUser(), "批量删除Bom", model.getClientIp(),
                new Timestamp(System.currentTimeMillis())
        , tipType, "批量删除BomID为  "+ model.getBomIDs() + " " + tipMsg + "！", "批量删除Bom" + tipMsg));
	    return SUCCESS;
	}

    /**
     * 批量设置状态-启用或者禁用
     * @return
     */
    public String batchSetEnable()
    {
        try
        {
        	BomService.batchSetEnable(model.getEnabled(),model.getBomIDs());
            model.getShowModel().setMsgTip("成功");
            //记录操作日志使用
            tipMsg = "成功";
            tipType = 0;
        }
        catch (DataAccessException e)
        {
            Log.errorFileSync(">>>>>>>>>>>批量修改状态，单位ID为：" + model.getBomIDs() + "信息异常", e);
            tipMsg = "失败";
            tipType = 1;
        }

        logService.create(new Logdetails(getUser(), "批量修改单位状态", model.getClientIp(),
                new Timestamp(System.currentTimeMillis())
                , tipType, "批量修改状态，单位ID为  "+ model.getBomIDs() + " " + tipMsg + "！", "批量修改单位状态" + tipMsg));
        return SUCCESS;
    }
    
	/**
	 * 检查输入名称是否存在
	 */
	public void checkIsNameExist()
	{
	    Boolean flag = false;
	    try 
	    {
	       // flag = BomService.checkIsNameExist("item",model.getItem(),"id", model.getBomID());
        } 
	    catch (DataAccessException e) 
	    {
            Log.errorFileSync(">>>>>>>>>>>>>>>>>检查Bom名称为：" + model.getItem() + " ID为： " + model.getItem() + " 是否存在异常！");
        }
	    finally
	    {
	        try 
	        {
                toClient(flag.toString());
            }
	        catch (IOException e) 
	        {
                Log.errorFileSync(">>>>>>>>>>>>回写检查Bom名称为：" + model.getItem() + " ID为： " + model.getItem() + " 是否存在异常！",e);
            }
	    }
	}
	/**
	 * 查找Bom信息
	 * @return
	 */
    public void findBy()
	{
	    try 
	    {
	        PageUtil<Bom> pageUtil = new  PageUtil<Bom>();
            pageUtil.setPageSize(model.getPageSize());
            pageUtil.setCurPage(model.getPageNo());
            pageUtil.setAdvSearch(getCondition());
            BomService.find(pageUtil);
            String sName = "";
            sName = "pageUtilVendor";
            getSession().put(sName, pageUtil);
            List<Bom> dataList = pageUtil.getPageList();
            
            JSONObject outer = new JSONObject();
            outer.put("total", pageUtil.getTotalCount());
            //存放数据json数组
            JSONArray dataArray = new JSONArray();
            if(null != dataList)
            {
                for(Bom bom:dataList)
                {
                    JSONObject item = new JSONObject();
                    item.put("id", bom.getId());
                    //供应商名称
                    item.put("item", bom.getItem());
                    item.put("qty", bom.getQty());
                    item.put("ref_designator",bom.getRef_designator());
                    item.put("complete_part", bom.getComplete_part());
                    item.put("description", bom.getDescription());
                    item.put("pakage_type_or_doc_type",bom.getPakage_type_or_doc_type());
                    item.put("value_or_rev",bom.getValue_or_rev());
                    item.put("voltage",bom.getVoltage());
                    item.put("isystem", bom.getIsystem() == (short)0?"是":"否");

                    item.put("tolerances", bom.getTolerances());
                    item.put("special_comments", bom.getSpecial_comments());
                    item.put("rohs", bom.getRohs());
                    item.put("temperature_range", bom.getTemperature_range());
                    item.put("manufacturer", bom.getManufacturer());
                    item.put("supplier", bom.getSupplier());
                    item.put("supplier_part_no", bom.getSupplier_part_no());
                    item.put("second_source_manufacturer", bom.getSecond_source_manufacturer());
                    item.put("second_source_part_no", bom.getSecond_source_part_no());
                    item.put("dr_rart_number", bom.getDr_rart_number());

                    item.put("enabled", bom.getEnabled());
                    item.put("op", bom.getIsystem());
                    dataArray.add(item);
                }
            }
            outer.put("rows", dataArray);
            //回写查询结果
            toClient(outer.toString());
        } 
	    catch (DataAccessException e) 
	    {
	        Log.errorFileSync(">>>>>>>>>查找供应商信息异常", e);
        } 
	    catch (IOException e) 
	    {
            Log.errorFileSync(">>>>>>>>>回写查询供应商信息结果异常", e);
        }
	}

	public String importFun(){
        //excel表格file
        Boolean result = false;
        String returnStr = "";
        try {
            InputStream in = BomService.importExcel(model.getBomFile());

            if(null != in)
            {
                model.setFileName(Tools.getRandomChar() + Tools.getNow2(Calendar.getInstance().getTime()) + "_wrong.xls");
                model.setExcelStream(in);
                returnStr = BomConstants.BusinessForExcel.EXCEL;
            }
            else {
                result = true;
                try {
                    toClient(result.toString());
                } catch (IOException e) {
                    Log.errorFileSync(">>>>>>>>>回写导入信息结果异常", e);
                }
                //导入数据成功
                returnStr = SUCCESS;
            }

        }
        catch (JshException e)
        {
            Log.errorFileSync(">>>>>>>>>>>>>>>>>>>导入excel表格信息异常", e);
        }
        return returnStr;
    }

    /**
     * 导入excel表格-Bom
     * @return
     */
    @SuppressWarnings("unchecked")
    public String importExcelBom() {
        return importFun();
    }


    /**
     * 导出excel表格
     * @return
     */
    @SuppressWarnings("unchecked")
    public String exportExcel() {
        Log.infoFileSync("===================调用导出信息action方法exportExcel开始=======================");
        try {
            String sName = "pageUtil" + "Vendor";
            PageUtil<Bom> pageUtil = (PageUtil<Bom>)getSession().get(sName);
            
          //  pageUtil.setPageSize(model.getPageSize());
          //  pageUtil.setCurPage(model.getPageNo());
       //     System.out.println(model.getPageNo());
            String isCurrentPage = "allPage";
            model.setFileName(Tools.changeUnicode("BOM" + System.currentTimeMillis() + ".xls",model.getBrowserType()));
            model.setExcelStream(BomService.exmportExcel(isCurrentPage,pageUtil));
        }
        catch (Exception e) {
            Log.errorFileSync(">>>>>>>>>>>>>>>>>>>>>>调用导出信息action方法exportExcel异常",e);
            model.getShowModel().setMsgTip("export excel exception");
        }
        Log.infoFileSync("===================调用导出信息action方法exportExcel结束==================");
        return EXCEL;
    }
	/**
	 * 拼接搜索条件
	 * @return
	 */
	private Map<String,Object> getCondition() {
        /**
         * 拼接搜索条件
         */
        Map<String,Object> condition = new HashMap<String,Object>();
        condition.put("item_s_like", model.getItem());
        condition.put("qty_s_like",model.getQty());
        condition.put("description_s_like", model.getDescription());
        condition.put("voltage_s_like", model.getVoltage());
        condition.put("isystem_n_eq", ISYSTEM);
        condition.put("id_s_order", "desc");
        return condition;
    }

    /**
    *搜索条件
     */
    private Map<String,Object> getConditionById() {
        /**
         * 拼接搜索条件
         */
        Map<String,Object> condition = new HashMap<String,Object>();
        condition.put("Id_n_eq", model.getBomID());
        return condition;
    }
	
	/**
	 * 拼接搜索条件-下拉框-供应商
	 * @return
	 */
	private Map<String,Object> getCondition_Select_sup()
    {
        /**
         * 拼接搜索条件
         */
        Map<String,Object> condition = new HashMap<String,Object>();
        condition.put("type_s_like", "Bom");
        condition.put("enabled_s_eq",1);
        condition.put("id_s_order", "desc");
        return condition;
    }
    
	public void getInfomation(){
		
		Log.infoFileSync("===================调用获取excel表头字段action方法getInfomation开始=======================");
		HSSFWorkbook workbook = null;
		HashMap<String,ArrayList<String>> datamap = new HashMap<String,ArrayList<String>>();
		try {
			workbook = new HSSFWorkbook(new FileInputStream(model.getBomFile()));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//创建对工作表的引用,获取第一个工作表的内容
		HSSFSheet sheet = workbook.getSheetAt(0); ;
		Row row = null; 
		row = sheet.getRow(0);
//		int lastRowNum = sheet.getLastRowNum(); 
		Iterator<Cell> it = row.cellIterator();
		//资产子类型--添加了一些excel表格数据
		Cell cell = null;
        ArrayList<String> list = new ArrayList<String>();
		while(it.hasNext()) {
			//获取每个单元格对象
			cell = it.next();
			
			//设置此单元格为字符串类型
			cell.setCellType(Cell.CELL_TYPE_STRING);
			
			list.add(cell.getStringCellValue());
		}

		
//		for(int i=0;i<list.size();i++){	
//			ArrayList<String> value = new ArrayList<String>();
//			for(int j=1;j<=lastRowNum;j++){
//				row = sheet.getRow(j);
//				cell = row.getCell(i);  
//				//设置此单元格为字符串类型
//				cell.setCellType(Cell.CELL_TYPE_STRING);
//				String cellValue = cell.getStringCellValue(); 
//				value.add(cellValue);
//			}
//			datamap.put(list.get(i),value);
//			
//		}
		datamap.put("Header",list);
		jsonObject = JSONObject.fromObject(datamap);

		Log.infoFileSync("===================调用获取excel表头字段action方法getInfomation结束=======================");   
		
        //3、将json对象转化为json字符串
        try {
        	System.out.println(jsonObject.toString().replace("\\n", " "));
			toClient(jsonObject.toString().replace("\\n", " "));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static JSONObject doGetStr(String url) throws ClientProtocolException,IOException {
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(url);
		JSONObject jsonObject = null;
		HttpResponse response = client.execute(httpost);
		HttpEntity entity = response.getEntity();
		if(entity  != null){
			
			String result = EntityUtils.toString(response.getEntity());
			System.out.println(result);
			jsonObject = JSONObject.fromObject(result);
		}
		return jsonObject;
	}
	
	public void getData() throws ClientProtocolException,IOException{
		Authorization authorization = authorizationService.findToken();
		String url = "https://sso.digikey.com/as/token.oauth2?client_id=6ca977ca-678d-48f1-9a0a-d352bd35933d&"
	    		+ "client_secret=aS4hW6iW8aB8jA6kQ7gF8vU4mV0wK5gY1sE5oK8jW8xQ4uB1cH&code=qlFXeu9_HvF6nTv8s5ozyEkHDWaKgjBhF6LauAAE"
	    		+ "grant_type=authorization_code&redirect_uri=https://mail.qq.com";
		
		//String url = TokenURL + authorization.getRefresh_token();
	    JSONObject jsonobject = doGetStr(url);
		
	    System.out.println(jsonObject.toString());
	}
	
	
	
	//=============以下spring注入以及Model驱动公共方法，与Action处理无关==================
	@Override
	public BomModel getModel()
	{
		return model;
	}
	

	
	public JSONObject getJsonObject() {
		return jsonObject;
	}
	public void setJsonObject(JSONObject jsonObject) {
		this.jsonObject = jsonObject;
	}
	
	public void setBomService(BomService BomService)
	{
		this.BomService = BomService;
	}
	
	public void setAuthorizationService(AuthorizationIService authorizationService) {
		this.authorizationService = authorizationService;
	}
	public void setUserBusinessService(UserBusinessIService userBusinessService) {
        this.userBusinessService = userBusinessService;
    }
    
   
}
